import paramiko
import os

def upload_file_to_server(local_path, remote_path, hostname, port, username, password):
    # 创建SSH客户端
    client = paramiko.SSHClient()

    # 自动添加和保存远程服务器的主机密钥
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程服务器
        client.connect(hostname=hostname, port=port, username=username, password=password)

        # 创建SFTP客户端
        sftp = client.open_sftp()

        # 上传文件
        sftp.put(local_path, remote_path)

        print("文件上传成功！")
        return 1, "upload successfully"
    except Exception as e:
        print("文件上传失败:", str(e))
        return -1, e

    finally:
        # 关闭连接
        if client:
            client.close()

def download_file_from_server(remote_path, local_path, hostname, port, username, password):
    # 创建SSH客户端
    client = paramiko.SSHClient()

    # 自动添加和保存远程服务器的主机密钥
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接远程服务器
        client.connect(hostname=hostname, port=port, username=username, password=password)

        # 创建SFTP客户端
        sftp = client.open_sftp()

        # 下载文件
        sftp.get(remote_path, local_path)

        print("文件下载成功！")

    except Exception as e:
        print("文件下载失败:", str(e))

    finally:
        # 关闭连接
        if client:
            client.close()


